<template>
  <div v-loading="loading">
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
        <!-- <a-button>
                    导出模板
                </a-button>
                <a-button>
                    导入
                </a-button> -->
      </template>
      <excel
        ref="exportSelect"
        file-name="处置明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="处置明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['estSize', 'estUnitPrice', 'amount', 'disposalReason']"
        :slot="col"
        slot-scope="text, record"
      >
        <div
          :key="col"
          :class="{ 'form-item': col !== 'disposalReason' }"
        >
          <template v-if="state != 3">
            <BaseInput
              v-if="col === 'disposalReason'"
              :value="text"
              :disabled="col === 'amount'"
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estUnitPrice' || col === 'amount'"
              v-model="record[col]"
              :precision="2"
              :min="0"
              :disabled="col === 'amount'"
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estSize'"
              v-model="record[col]"
              :precision="3"
              :min="0"
              :disabled="col === 'amount'"
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              :precision="2"
              :min="0"
              :disabled="col === 'amount'"
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <!-- 物料选择 -->
    <materialListAndDir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
  disposalDetailList,
  disposalDetailDel,
  disposalDetailEdit,
  disposalDetailAddBatch
} from '@/api/material/remaining/disposal'
import { columns } from './insideModel'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'

const data = []
export default {
  name: 'a' + Date.now(),
  components: {
    materialListAndDir
  },
  props: {
    state: {
      type: Number
    },
    id: {
      type: String
    }
  },
  data() {
    this.cacheData = data.map((item) => ({ ...item }))
    return {
      loading: false,
      selectedRows: [],
      pageNo: 1,
      pageSize: 10,
      queryParam: {},
      totalSize: 0,
      selectedRowKeys: [],
      columns: columns,
      editingKey: '',
      data: [],
      selectedId: [],
      rules: {
        estSize: [{ rule: 'required', message: '暂估数量不能为空' }],
        estUnitPrice: [{ rule: 'required', message: '暂估单价不能为空' }]
      }
    }
  },
  mounted: function () {
    if (this.state === 3) {
      this.editingKey = true
    }
    this.list()
    this.initErrMessage(this.rules)
    this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
    this.$refs.exportAll.tableToExcelFile(this.$refs.table)
  },
  methods: {
    /**
     * @description: 获取全部列表
     */
    async getAll(callback, errorCallback) {
      let total = this.totalSize
      console.log('123')
      if (total > 0) {
        let res = await disposalDetailList({
          pageSize: this.totalSize,
          pageNo: 1,
          disposalApplyId: this.id
        })
        if (res.code !== this.SUCCESS_CODE) {
          errorCallback && errorCallback(res)
          return
        } else {
          callback && callback(res)
        }
      } else {
        callback && callback({ data: [] })
      }
    },
    exportSelect: function () {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
      } else {
        this.$message.warning('请选择需要导出的数据')
      }
    },
    exportAll: function () {
      // 参数：查询条件、导出的回调
      if (this.totalSize) {
        this.pageNo = 1
        this.list(this.$refs.exportAll.setDataAndGenerate)
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    openDailog: function () {
      if (this.editingKey !== '') {
        this.$message.error('新增前请结束当前操作行')
        return
      }
      this.getAll((res) => {
        this.$refs.detailDialog.open(res.data)
      })
    },
    createList: function (selectRows) {
      let _this = this
      let form = this.$clone(selectRows)
      form.forEach((item) => {
        item.materialId = item.id
        item.materialName = item.name
        item.materialCode = item.code
        item.materialModel = item.specificationModel
        item.materialUnit = item.unit
        item.disposalApplyId = this.id
        delete item.id
      })
      disposalDetailAddBatch(form).then((res) => {
        if (res.code === 200) {
          _this.list()
        }
      })
    },
    // 删除
    handleDel() {
      this.$confirm({
        title: '确定是否删除数据？',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          return disposalDetailDel({ ids: this.selectedId }).then((res) => {
            if (res.data.code === 200) {
              this.initTable()
              this.selectedId = []
              this.selectedRowKeys = []
              this.selectedRows = []
              this.editingKey = ''
              this.$message.success('删除成功！')
            }
          })
        }
      })
    },
    initTable() {
      this.pageNo = 1
      this.list()
    },
    list(callback) {
      this.loading = true
      let _this = this
      disposalDetailList({
        pageSize: callback ? _this.totalSize : _this.pageSize,
        pageNo: _this.pageNo,
        disposalApplyId: _this.id
      }).then((res) => {
        if (res.code === 200) {
          if (callback) {
            if (res.data.length) {
              callback(res.data)
            } else {
              this.$message.warning('没有可导出的数据')
            }
            this.loading = false
            return
          }
          _this.data = res.data
          _this.totalSize = res.totalSize
          this.cacheData = res.data.map((item) => ({ ...item }))
        }
        this.loading = false
      })
    },
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.id)[0]
      if (target) {
        target[column] = value
        target['amount'] = target['estSize'] * target['estUnitPrice']
        target['amount'] = target['amount'].toFixed(2)
        // if (this.rules[column]) {
        //   this.customValidation(value, column)
        // }
        this.data = newData
      }
      this.save(key)
    },
    edit(key) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.id)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRowKeys = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageSize = pageSize
      this.initTable()
    },
    save(key) {
      // 编辑保存
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter((item) => key === item.id)[0]
      // for (let key in target) {
      //   if (this.rules[key]) {
      //     this.customValidation(target[key], key)
      //   }
      // }
      // for (let i in this.customValidationErr) {
      //   if (i) {
      //     return
      //   }
      // }
      // this.loading = true
      target.baseId = this.id
      disposalDetailEdit(target).then((res) => {
        if (res.code === 200) {
          // this.$message.success('保存成功')
          // this.initTable()
        }
        // this.loading = false
      })
      const targetCache = newCacheData.filter((item) => key === item.id)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedId = []
      selectedRows.map((i) => {
        this.selectedId.push(i.id)
      })
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    cancel(key) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.id)[0]
      this.editingKey = ''
      if (target) {
        if (target.isAdd) {
          newData.splice(0, 1)
        } else {
          Object.assign(target, this.cacheData.filter((item) => key === item.id)[0])
          target.editable = false
          delete target.editable
        }
        this.data = newData
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .form-item {
  .ant-input:not([disabled]),
  .ant-time-picker-input,
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number-input:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
</style>
